#!/bin/bash

###run this script to adjust License info,and automatically
###adapt spec file for submit.
###parameter:
###           project_name: project name which should contain a spec file
###           old_license : license info which should be replaced with a new one
###           new_license : new license info
###           submitter   : author info used to generate changelog
###           mail        : e mail address used to genertae changelog
###output   : project_name.spec
###author   : Wang Ge
###date     : 2024-06-12

Usage="Usage  : $0 project_path old_license new_license submitter mail"
Exam="Example: ./Change_Spec_License 'bval' 'ASL 2.0' 'Apache-2.0' 'Ge Wang' '<wang__ge@126.com>'"

PROJ_NAME="$1"
SPEC_NAME="$1/$1.spec"
OLD_LICENSE=$2
NEW_LICENSE=$3
DATE_INFO=$(date | awk '{print $1" "$2" "$3" "$7}')
SUBMITTER=$4
MAIL_ADDR=$5

if [ $# -ne 5 ]; then
  echo $Usage
  echo $Exam
  exit 1
fi

if [ ! -d "$PROJ_NAME" ];then
  echo "Error: project folder not found"
  exit 1
fi

if [ ! -f "$SPEC_NAME" ]; then
  echo "Error: no valid spec file $SPEC_NAME"
  exit 1
fi

VERSION_NUM=$(grep -rnA1 "changelog" $SPEC_NAME | sed -n "2, 1p" | awk '{print $NF}' | awk -F- '{print $1}')
RELEASE_NUM=$(grep -rn 'Release:' $SPEC_NAME | awk -F: '{print $3}' | eval echo `xargs`)
NEW_RELEASE=$((RELEASE_NUM + 1))

grep -rnc "$OLD_LICENSE" $SPEC_NAME > /dev/null 2>&1
if [ $? != 0 ]; then
  echo "Error: no specified license info found in file $SPEC_NAME"
  exit 1
fi
sed -i "/Release:/s/${RELEASE_NUM}/${NEW_RELEASE}/g" $SPEC_NAME
sed -i "s/${OLD_LICENSE}/${NEW_LICENSE}/g" $SPEC_NAME
sed -i "/%changelog/a * ${DATE_INFO} ${SUBMITTER} ${MAIL_ADDR} - ${VERSION_NUM}-${NEW_RELEASE}" $SPEC_NAME
sed -i "/${VERSION_NUM}-${NEW_RELEASE}/a - Regulate license information" $SPEC_NAME
sed -i "/Regulate license information/G" $SPEC_NAME

